
#import "IOSFlutterView.h"
#import "MTCaptureSessionManager.h"


#import <Masonry/Masonry.h>

#import <HTEffect/HTEffectInterface.h>
#import <HTEffect/HTEffectView.h>
#import <HTEffect/HTEffect.h>

#define window_width  [UIScreen mainScreen].bounds.size.width
#define window_height  [UIScreen mainScreen].bounds.size.height

@interface IOSFlutterView()<MTCaptureSessionManagerDelegate,HTEffectDelegate>

@property(nonatomic, strong) CIImage *outputImage;
@property(nonatomic, assign) CVPixelBufferRef outputImagePixelBuffer;

@property(nonatomic,assign)BOOL isRenderInit;
@property(nonatomic,assign)BOOL isCameraSwitched;

@property (nonatomic, strong) HTEffectView *htLiveView;

@end

@implementation IOSFlutterView

- (HTEffectView *)htLiveView{
    if (!_htLiveView) {
        _htLiveView = [[HTEffectView alloc] init];
        _htLiveView.contentMode = HTEffectViewContentModeScaleAspectFill;
        _htLiveView.orientation = HTEffectViewOrientationLandscapeLeft;
        _htLiveView.userInteractionEnabled = YES;
    }
    return _htLiveView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
        [self initSDK];
    }
    return self;
}

- (void)initSDK{

    //todo ---HTEffect--- 初始化SDK
    [[HTEffect shareInstance] initHTEffect:@"<YOUR_APP_ID>" withDelegate:self];

    [[MTCaptureSessionManager shareManager] startAVCaptureDelegate:self];
    
    self.userInteractionEnabled = YES;
    

}

- (void)setUI{
    
    [self addSubview:self.htLiveView];
    CGFloat imageOnPreviewScale = MAX(window_width / AV_CAPTURE_SESSION_PRESET_WIDTH, window_height / AV_CAPTURE_SESSION_PRESET_HEIGHT);
    CGFloat previewImageWidth = AV_CAPTURE_SESSION_PRESET_WIDTH * imageOnPreviewScale;
    CGFloat previewImageHeight = AV_CAPTURE_SESSION_PRESET_HEIGHT * imageOnPreviewScale;

    [self.htLiveView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(previewImageWidth);
        make.height.mas_equalTo(previewImageHeight);
    }];
}

// MARK: --HTEffectDelegate Delegate--

- (void)onInitSuccess{
    NSLog(@"HTEffect 加载成功");
    [self initBeautyData];
}

- (void)onInitFailure{
    NSLog(@"HTEffect 加载失败");
}

- (void)initBeautyData{
    //开启美颜渲染
    [[HTEffect shareInstance] setRenderEnable:true];
    
    [[HTEffect shareInstance] setBeauty:HTBeautySkinWhitening value:70];
    [[HTEffect shareInstance] setBeauty:HTBeautyClearSmoothing value:80];
    [[HTEffect shareInstance] setBeauty:HTBeautySkinRosiness value:10];
    [[HTEffect shareInstance] setBeauty:HTBeautyImageSharpness value:5];
    [[HTEffect shareInstance] setBeauty:HTBeautyImageBrightness value:0];
    
    [[HTEffect shareInstance] setReshape:HTReshapeEyeEnlarging value:60];
    [[HTEffect shareInstance] setReshape:HTReshapeCheekThinning value:30];
    [[HTEffect shareInstance] setReshape:HTReshapeCheekVShaping value:50];

    [[HTEffect shareInstance] setFilter:HTFilterBeauty name:@"ziran3"];
}

/**
 * 切换摄像头
 */
- (void)didClickSwitchCameraButton:(UIButton *)sender{
    
    sender.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    [[MTCaptureSessionManager shareManager] didClickSwitchCameraButton];
    _isCameraSwitched = true;
    
}

// MARK: --MTCaptureSessionManager Delegate--

-(void)captureSampleBuffer:(CMSampleBufferRef)sampleBuffer Rotation:(NSInteger)rotation Mirror:(BOOL)isMirror{
    
    CVPixelBufferRef pixelBuffer = (CVPixelBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
       if (pixelBuffer == NULL) {
           return;
       }
      CVPixelBufferLockBaseAddress(pixelBuffer, 0);
     unsigned char *baseAddress = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
    
    // 视频帧格式
    HTFormatEnum format;
       switch (CVPixelBufferGetPixelFormatType(pixelBuffer)) {
           case kCVPixelFormatType_32BGRA:
               format = HTFormatBGRA;
               break;
           case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
               format = HTFormatNV12;
               break;
           case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
               format = HTFormatNV12;
               break;
           default:
               NSLog(@"错误的视频帧格式！");
               format = HTFormatBGRA;
               break;
       }
    int imageWidth, imageHeight;
    if (format == HTFormatBGRA) {
        imageWidth = (int)CVPixelBufferGetBytesPerRow(pixelBuffer) / 4;
        imageHeight = (int)CVPixelBufferGetHeight(pixelBuffer);
    } else {
        imageWidth = (int)CVPixelBufferGetWidthOfPlane(pixelBuffer , 0);
        imageHeight = (int)CVPixelBufferGetHeightOfPlane(pixelBuffer , 0);
    }
    if (_isCameraSwitched) {
        [[HTEffect shareInstance] releaseBufferRenderer];
        _isCameraSwitched = false;
        _isRenderInit = false;
    }
    //todo ---HTEffect---
    //添加渲染
    if (!_isRenderInit) {
        _isRenderInit = [[HTEffect shareInstance] initBufferRenderer:HTFormatBGRA width:imageWidth height:imageHeight rotation:HTRotationClockwise90 isMirror:isMirror maxFaces:5];
    }
    
    [[HTEffect shareInstance] processBuffer:baseAddress];
    
    [self.htLiveView displayPixelBuffer:pixelBuffer isMirror:isMirror];
    
    self.outputImage = [CIImage imageWithCVPixelBuffer:pixelBuffer];
    self.outputImagePixelBuffer = pixelBuffer;
    
    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
    
}

- (void)dealloc {
    [[HTEffect shareInstance] releaseBufferRenderer];
}


@end
